package com.example.swimfish;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

import static com.example.swimfish.PeerDiscoveryServer.DISCOVERY_MESSAGE;
import static com.example.swimfish.PeerDiscoveryServer.DISCOVERY_PORT;


public class NetworkUtils {

    // 获取本地局域网IP地址
    public static String getLocalIP() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iface = interfaces.nextElement();
                if (iface.isLoopback() || !iface.isUp()) continue;

                Enumeration<InetAddress> addresses = iface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr.isSiteLocalAddress()) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }
    //本地网络发现 非局域网
    public static List<String> discoverPeersUsingUDP() {
        List<String> peers = new ArrayList<>();
        try {
            DatagramSocket socket = new DatagramSocket();
            socket.setBroadcast(true);

            // 发送发现请求
            byte[] sendData = DISCOVERY_MESSAGE.getBytes();
            InetAddress broadcast = InetAddress.getByName("255.255.255.255");
            DatagramPacket sendPacket = new DatagramPacket(
                    sendData, sendData.length, broadcast, DISCOVERY_PORT);
            socket.send(sendPacket);

            socket.setSoTimeout(1000); // 等待1秒响应

            byte[] recvBuf = new byte[1024];
            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
                try {
                    socket.receive(receivePacket);
                    // 解析响应内容为IP地址
                    String peerIP = new String(
                            receivePacket.getData(),
                            0,
                            receivePacket.getLength()
                    ).trim();

                    if (!peerIP.equals(getLocalIP())) {
                        peers.add(peerIP);
                    }
                } catch (SocketTimeoutException e) {
                    break;
                }
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return peers;
    }
    private static boolean isReachable(String ip) {
        System.out.println(2);
        try {
            return InetAddress.getByName(ip).isReachable(1);
        } catch (Exception e) {
            System.err.println("isReachable 发生异常: " + e.getMessage());
            return false;
        }
    }
}